var base = require('/base_info.js');
var utils = require('/utils/index.js');
var commom = require('/utils/common.js');
Page({
  data: {
    barList: [{
      'name': '全部',
      'index': '0'
    }, {
      'name': '待支付',
      'index': '1'
    }, {
      'name': '未入住',
      'index': '2'
    }, {
      'name': '待评价',
      'index': '9'
    }, {
      'name': '已完成',
      'index': '4'
    }],
    barIndex: 0,
    orderList: [],
    imgUrl: base.imgUrl,
    page: 1,
    pageNumber: 7,
    status: 0
  },
  getData() {
    let that = this;
    my.showLoading();
    utils.getData('SingleMyOrder', {
      user_id: my.getStorageSync({
        key: 'uid', // 缓存数据的key
      }).data,
      page: that.data.page,
      size: that.data.pageNumber,
      status: that.data.status
    }, (res) => {
      console.log(res.data.data);
      my.hideLoading({
        page: that,  // 防止执行时已经切换到其它页面，page指向不准确
      });
      res.data.data.forEach((element, index) => {
        res.data.data[index].CNstatus = that.orderStatus(element.status * 1);
        res.data.data[index].arrival_time = element.arrival_time.slice(5, 10);
        res.data.data[index].departure_time = element.departure_time.slice(5, 10);
        res.data.data[index].residue = commom.timeDown(element.time * 1000);
      });
      that.setData({
        orderList: that.data.orderList.concat(res.data.data)
      });
    }, (err) => {
      my.hideLoading();
      console.log(err);
    });
  },
  // 切换选项卡
  changeBar (e) {
    this.setData({
      barIndex: e.currentTarget.dataset.index,
      orderList: [],
      status: e.currentTarget.dataset.status,
      page: 1
    });
    // 重新获取数据
    this.getData();
  },
  // 跳转到订单详情页
  orderDetail (e) {
    console.log(e);
    my.navigateTo({
      url: './order-detail?id=' + e.currentTarget.dataset.id
    });
  },
  orderStatus (val) {
    let result = '';
    switch (val) {
      case 1:
        result = '待支付';
        break;
      case 2:
        result = '未入住';
        break;
      case 3:
        result = '已取消';
        break;
      case 4:
        result = '已完成';
        break;
      case 9:
        result = '待评价';
        break;
      case 6:
        result = '退款中';
        break;
      case 5:
        result = '待消费';
        break;
      case 7:
        result = '已退款';
        break;
    }
    return result;
  },
  // 请求后重置数据
  resetData () {
    console.log(1);
    this.setData({
      page: 1,
      orderList: []
    });
    this.getData();
  },
  // 删除订单
  delete(e) {
    let that = this;
    my.confirm({
      title: '',
      content: '订单一旦删除将无法恢复,是否确定删除该订单？',
      confirmButtonText: '是',
      cancelButtonText: '否',
      success: (result) => {
        if (result.confirm) {
          my.showLoading();
          utils.getData('SingleOrderDel', {
            order_id: e.currentTarget.dataset.id
          }, (res) => {
            my.hideLoading();
            if (res.data.errno == 1) {
              my.alert({
                title: `订单已成功删除`,
                success: () => {
                  that.resetData();
                }
              });
              return false;
            }
            my.alert({
              title: `${res.data.message}`,
            });
          }, (err) => {
            my.hideLoading();
            my.alert({
              title: `网络错误，请稍后再试`,
            });
          });
        }
      }
    });
  },
  // 取消申请退款
  cancelRefund (e) {
    let that = this;
    my.showLoading();
    utils.getData('SingleCancelApplyRefund', {
      order_id: e.currentTarget.dataset.id
    }, (res) => {
      my.hideLoading();
      if (res.data.errno == 1) {
        my.alert({
          title: `已成功取消申请`,
          success: () => {
            that.resetData();
          }
        });
        return false;
      }
      my.alert({
        title: `${res.data.message}`,
      });
    }, (err) => {
      my.hideLoading();
      my.alert({
        title: `网络错误，请稍后再试`,
      });
    });
  },
  // 取消订单 
  cancel(e) {
    let that = this;
    my.confirm({
      title: '',
      content: '订单一旦取消将需要重新预订,是否确定取消该订单？',
      confirmButtonText: '是',
      cancelButtonText: '否',
      success: (result) => {
        if (result.confirm) {
          my.showLoading();
          utils.getData('SingleCancelOrder', {
            order_id: e.currentTarget.dataset.id
          }, (res) => {
            my.hideLoading();
            if (res.data.errno == 1) {
              my.alert({
                title: `订单已成功取消`,
                success: () => {
                  that.resetData();
                }
              });
              return false;
            }
            my.alert({
              title: `${res.data.message}`,
            });
          }, (err) => {
            my.hideLoading();
            my.alert({
              title: `网络错误，请稍后再试`,
            });
          });
        }
      },
    });
  },
  // 去支付
  pay(e) {
    // 调用支付
    let that = this;
    my.showLoading();
    new Promise((resolve, reject) => {
      utils.getData('SingleOrderStatus', {
        order_id: e.currentTarget.dataset.id
      }, (res) => {
        if (res.data.data.status == 1) {
          resolve(1);
          return false;
        };
        reject(1);
      }, err => {
        reject(1);
      })
    }).then(() => {
      // 如果是预授权
      if (e.currentTarget.dataset.method == 2) {
        my.tradePay({
          orderStr: e.currentTarget.dataset.orderStr,
          success: (res) => {
            my.hideLoading();
            if (res.resultCode == 9000) {
              my.alert({
                content: '支付成功',
                success: () => {
                  that.resetData();
                }
              });
            } else {
              my.alert({
                content: '支付失败'
              });
            }
          },
          fail: (res) => {
            my.hideLoading();
            my.alert({
              content: '支付失败',
            });
          }
        });
        return false;
      }
      // 如果是普通支付
      my.tradePay({
        tradeNO: e.currentTarget.dataset.orderNo,
        success: (res) => {
          my.hideLoading();
          if (res.resultCode == 9000) {
            my.alert({
              content: '支付成功'
            });
          } else {
            my.alert({
              content: '支付失败'
            });
          }
        },
        fail: (res) => {
          my.hideLoading();
          my.alert({
            content: '支付失败',
          });
        }
      });
    }, (err) => {
      my.hideLoading();
      my.alert({
        content: '该订单不可以支付' 
      });
    })
  },
  // 申请退款
  refund(e) {
    // 调转到申请退款页面
    my.navigateTo({
      url: './order-refund?id=' + e.currentTarget.dataset.id
    });
  },
  // 去评价
  comment(e) {
    // 跳转到去评价页面
    my.navigateTo({
      url: './order-comment?id=' + e.currentTarget.dataset.id
    })
  },
  onLoad(query) {
    console.log(query);
    var that = this;
    this.setData({
      barIndex: query.index ? query.index : 0,
      status: query.id ? query.id : 0
    });
    setInterval(function () {
      var data = that.data.orderList;
      data.forEach((element, index) => {
        data[index].residue = commom.timeDown(element.time * 1000);
        if (data[index].residue == 0 && data[index].status == 1) {
          data[index].status = 3;
          data[index].CNstatus = '已取消';
        };
      });
      that.setData({
        orderList: data
      });
    }, 1000);
    // 页面加载
    // this.getData();
  },
  onReady() {
    // 页面加载完成
  },
  onShow() {
    // 页面显示
    this.resetData();
  },
  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
    this.setData({
      page: this.data.page + 1
    });
    this.getData();
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: my.getStorageSync({
        key: 'hotel_name', // 缓存数据的key
      }).data,
      desc: my.getStorageSync({
        key: 'my_app_description', // 缓存数据的key
      }).data,
      path: 'pages/index/index?share=true',
      success: function (e) {
        console.log(e);
      }
    };
  },
});
